package com.xizi;


public class ThreadLocalExample {
    public static class MyRunnable implements Runnable {

        private ThreadLocal<Object> threadLocal = new ThreadLocal<>();

        //自定义对象
        class Obj {
            int value;
        }

        @Override
        public void run() {
            // 局部引用，可以相互隔离。
            Obj obj = new Obj();
            obj.value = (int) (Math.random() * 100D);
            threadLocal.set(obj);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println(e);
            }

            System.out.println(Thread.currentThread().getName() + "  " + ((Obj) threadLocal.get()).value);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        MyRunnable sharedRunnableInstance = new MyRunnable();

        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance);

        thread1.start();
        thread2.start();

        thread1.join(); //wait for thread 1 to terminate
        thread2.join(); //wait for thread 2 to terminate
    }
}
